<template>
  <div class="table-box">
    <div class="card table-search">
      <el-form ref="formRef" :model="searchParam">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="在线状态：">
              <el-select v-model="searchParam.state_list" @change="search">
                <el-option v-for="(item, index) of statusData" :key="index" :label="item.name" :value="item.name"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="账号分组：">
              <el-select v-model="searchParam.group_list" @change="search">
                <el-option v-for="(item, index) of accountData" :key="index" :label="item.name" :value="item.name"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="账号类别：">
              <el-select v-model="searchParam.type_list" @change="search">
                <el-option v-for="(item, index) of accountType" :key="index" :label="item.name" :value="item.name"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="card table-main">
      <div class="table-header" v-if="type">
        <div class="header-button-lf">
          <el-button type="primary" :disabled="!multipleSelection.length" @click="confirmSelect">确认选择</el-button>
        </div>
      </div>
      <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange" row-key="accountId" border>
        <el-table-column type="selection" width="60" align="center" v-if="type" :reserve-selection="true" />
        <el-table-column prop="accountState" label="在线状态" align="center" />
        <el-table-column prop="accountName" label="账号昵称" align="center" />
        <el-table-column prop="phoneGroup" label="组别名称" align="center" />
        <el-table-column prop="phoneName" label="所在云手机名称" align="center" />
        <el-table-column prop="mmId" label="微信id" align="center" />
        <template #empty>
          <div class="table-empty">
            <slot name="empty">
              <img src="@/assets/images/notData.png" alt="notData" />
              <div>暂无数据</div>
            </slot>
          </div>
        </template>
      </el-table>

      <el-pagination
        background
        layout="prev, pager, next, total"
        :total="total"
        v-model:current-page="query.page"
        v-model:page-size="query.size"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onBeforeUnmount } from "vue";
import { useRoute } from "vue-router";
import {
  getAccountGroupsApi,
  getAccountListApi,
  getAccountStatesApi,
  getAccountTypesApi,
  startLookTaskApi,
  startTaskApi,
  startVideoTaskApi,
  startWeTaskApi
} from "@/api/modules/business";
import { AccountList } from "@/api/interface";
import { useUserStore } from "@/stores/modules/user";
import { ElMessage, ElMessageBox } from "element-plus";

const route = useRoute();
const userStore = useUserStore();
const type = computed(() => route.query.type);
const formRef = ref<any>();
const searchParam = ref({
  state_list: "全部",
  group_list: "全部",
  type_list: "全部"
});
const statusData = ref<{ name: string }[]>([]);
const accountData = ref<{ name: string }[]>([]);
const accountType = ref<{ name: string }[]>([]);
const tableData = ref<AccountList[]>([]);
const total = ref(10);
const query = ref({ page: 1, size: 10 });
const multipleSelection = ref<Record<string, any>[]>([]);

function search() {
  console.log(searchParam.value);
  query.value.page = 1;
  getAccountData();
}

function handleSelectionChange(val: Record<string, any>[]) {
  multipleSelection.value = val;
}

function confirmSelect() {
  const addForm = userStore.taskInfo;
  addForm.accountList = multipleSelection.value.map(item => item.accountId);
  ElMessageBox.confirm("确认开始添加任务？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    let data = { result: false, message: "暂无任务" };
    if (type.value === "person") {
      data = await startTaskApi(addForm);
    } else if (type.value === "enterprise") {
      data = await startWeTaskApi(addForm);
    } else if (type.value === "browseChannels") {
      data = await startVideoTaskApi(addForm);
    } else if (type.value === "browseGlance") {
      data = await startLookTaskApi(addForm);
    }

    if (!data.result) return ElMessage.error(data.message);
    ElMessage.success(data.message || "操作成功");
  });
}

async function getAccountTypes() {
  const data = await getAccountTypesApi();
  accountType.value = data.typeList.map(item => {
    return { name: item };
  });
}

async function getAccountGroups() {
  const data = await getAccountGroupsApi();
  accountData.value = data.groupList.map(item => {
    return { name: item };
  });
}

async function getAccountStates() {
  const data = await getAccountStatesApi();
  statusData.value = data.stateList.map(item => {
    return { name: item };
  });
}

async function getAccountData() {
  const data = await getAccountListApi({
    ...query.value,
    with_messages: true,
    ...searchParam.value
  });
  tableData.value = data.data || [];
  total.value = data.total || 0;
}

function handleSizeChange(num: number) {
  query.value.page = 1;
  query.value.size = num;
  getAccountData();
}

function handleCurrentChange(num: number) {
  query.value.page = num;
  getAccountData();
}

getAccountTypes();
getAccountGroups();
getAccountStates();
getAccountData();

onBeforeUnmount(() => userStore.setTaskInfo({}));

defineOptions({ name: "SelectAccount" });
</script>
